<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    //解决查询字符串问题
    const ajax = (options) => {
      const resolveData = parnms => {
        if (!parnms) return ''
        const arr = new Array('?')
        for (const [key, val] of Object.entries(parnms)) {
          arr.push(`${key}=${val}`)
        }
        return arr.join('&')
      }
      //处理参数
      const method = options.type ? options.type.toUpperCase() : 'GET'
      const xhr = new XMLHttpRequest()
      if (method === 'GET') {
        const url = options.url + resolveData(options.data)
        xhr.open(method, url)
        xhr.send()
      } else {
        const data = resolveData(options.data).substring(1)
        const url = options.url
        xhr.open(method, url)
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        xhr.send(data)
      }

      xhr.addEventListener('load', () => {
        if (xhr.status === 200) {
          //请求成功，执行回调函数
          options.success(JSON.parse(xhr.responseText))
        }
      })
    }

    ajax({
      type: 'GET',
      url: 'http://www.liulongbin.top:3006/api/getbooks',
      data: {
        id: 3
      },
      success: function (res) {
        console.log(res)
      }
    })

    ajax({
      type: 'POST',
      url: 'http://www.liulongbin.top:3006/api/addbook',
      data: {
        bookname: 'a',
        author: 'b',
        publisher: 'c'
      },
      success: function (res) {
        console.log(res)
      }
    })
  </script>
</body>

</html>